package com.leyou.sms.mq;

import com.leyou.common.utils.RegexUtils;
import com.leyou.sms.config.SmsProperties;
import com.leyou.sms.utils.SmsUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Map;

import static com.leyou.common.constants.MQConstants.Exchange.SMS_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.Queue.SMS_VERIFY_CODE_QUEUE;
import static com.leyou.common.constants.MQConstants.RoutingKey.VERIFY_CODE_KEY;

@Slf4j
@Component
public class SmsListener {

    @Autowired
    private SmsUtils smsUtils;

    @Autowired
    private SmsProperties prop;

    //监听mq
    /**
     * 发送短信验证码监听器
     */
    @RabbitListener(bindings = @QueueBinding(
            value=@Queue(name = SMS_VERIFY_CODE_QUEUE, durable = "true"),
            exchange = @Exchange(name = SMS_EXCHANGE_NAME, type = ExchangeTypes.TOPIC),
            key = VERIFY_CODE_KEY
    ))
    public void listenerSms(Map<String,String> msg){
        try {
            //判空
            if (CollectionUtils.isEmpty(msg)){
                return;
            }
            //手机号码
            String phone = msg.get("phone");
            if (!RegexUtils.isPhone(phone)){
                return;
            }
            //验证码
            String code = msg.get("code");
            if (!RegexUtils.verifyCode(code)){
                return;
            }
            code = "{\"code\":\"" + code + "\"}";

            //发送短信
            smsUtils.sendMessage( phone, prop.getSignName(), prop.getVerifyCodeTemplate(), code);
        } catch (Exception e){
            log.error("【短信微服务】发送短信失败: {}",e.getMessage());
            e.printStackTrace();
        }
    }



}
